package his;

import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.dsl.ExecListener;
import io.fabric8.kubernetes.client.dsl.ExecWatch;
import okhttp3.Response;
import okhttp3.WebSocket;

public class ExecExample {
    public static void main(String[] args) {
        try (KubernetesClient client = new DefaultKubernetesClient()) {
            String namespace = "default"; // 替换为你的命名空间
            String podName = "your-pod-name"; // 替换为你的pod名称

            Pod pod = client.pods().inNamespace(namespace).withName(podName).get();
            if (pod != null) {
                // 使用 execWatch 执行命令
                try (ExecWatch watch = client.pods().inNamespace(namespace)
                        .withName(podName)
                        .writingOutput(System.out)
                        .writingError(System.err)
                        .usingListener(new MyExecListener())
                        .exec("sh", "-c", "echo Hello from the other side!")) {

                    // 等待命令执行完成
                    watch.close();
                }
            } else {
                System.out.println("Pod not found.");
            }
        }
    }

    // 自定义监听器，可以在这里处理输入输出等逻辑
    private static class MyExecListener implements ExecListener {

        @Override
        public void onOpen(Response response) {

        }

        @Override
        public void onFailure(Throwable t, Response response) {
            // 发生错误时调用
            t.printStackTrace();
        }

        @Override
        public void onClose(int code, String reason) {
            // 连接关闭时调用
        }
    }
}